package com.cakeshop.servelt;



import com.cakeshop.model.Order;
import com.cakeshop.model.User;
import com.cakeshop.service.OrderService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

@WebServlet(name = "OrderListMapServlet", value = "/ordermap")
public class OrderListMapServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String address = request.getParameter("address");
        System.out.println(address);
        try {
            URL url = new URL("https://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak=lnzv5GzmeqVe4d92VkrpFd6WOQzbrrIe&callback=showLocation");
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
            outputStreamWriter.flush();
            outputStreamWriter.close();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String str;
            StringBuilder stringBuilder = new StringBuilder("");
            while ((str = bufferedReader.readLine())!=null){
                stringBuilder.append(str.trim());
            }
            String datas = stringBuilder.toString();
            int lngindex = datas.indexOf("lng\":");
            int lngindex2 = datas.indexOf(",\"lat\":");
            double lng = Double.parseDouble(datas.substring(lngindex+5,lngindex2));
            int latindex = datas.indexOf("lat\":");
            int latindex2 = datas.indexOf("},\"precise\"");
            double lat = Double.parseDouble(datas.substring(latindex+5, latindex2));
            System.out.println(datas);
            System.out.println(lng);
            System.out.println(lat);
            request.setAttribute("lng",lng);
            request.setAttribute("lat",lat);
            request.getRequestDispatcher("order_map.jsp").forward(request,response);
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
